<template>
  <el-scrollbar height="97vh">
    <div class="dashboard-container">
    <!-- 顶部统计区域 -->
    <div class="stats-container" :class="{ 'stats-loaded': !isLoading }">
      <div class="stat-card primary-gradient">
        <div class="stat-icon">
          <el-icon><DataLine /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-value">{{ recordsCount }}</div>
          <div class="stat-title">总执行次数</div>
        </div>
      </div>

      <div class="stat-card success-gradient">
        <div class="stat-icon">
          <el-icon><Check /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-value">{{ totalSuccess }}</div>
          <div class="stat-title">通过用例</div>
        </div>
      </div>

      <div class="stat-card warning-gradient">
        <div class="stat-icon">
          <el-icon><Loading /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-value">{{ runningCount }}</div>
          <div class="stat-title">执行中</div>
        </div>
      </div>

      <div class="stat-card info-gradient">
        <div class="stat-icon">
          <el-icon><PieChart /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-value">{{ averagePassRate }}%</div>
          <div class="stat-title">平均通过率</div>
        </div>
      </div>
    </div>
      <!-- 图表和过滤器部分 -->
      <div class="chart-filter-container">
        <!-- 图表卡片 -->
        <div class="chart-card">
          <div class="card-header">
            <h3>测试通过率趋势</h3>
            <div class="time-selector">
              <el-radio-group v-model="timeRange" size="small" @change="handleTimeRangeChange">
                <el-radio-button label="day">当天</el-radio-button>
                <el-radio-button label="day3">近3天</el-radio-button>
                <el-radio-button label="week">近7天</el-radio-button>
                <el-radio-button label="month">近30天</el-radio-button>
                <el-radio-button label="all">全部</el-radio-button>
              </el-radio-group>
            </div>
          </div>
          <div class="chart-wrapper" ref="chart_box"></div>
        </div>

        <!-- 筛选卡片 -->
        <div class="filter-card">
          <div class="card-header">
            <h3>筛选条件</h3>
          </div>
          <div class="filter-content">
            <el-form label-position="top" size="small">
              <el-form-item label="执行时间" class="date-range-item">
                <el-date-picker
                  v-model="dataTime"
                  type="datetimerange"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  :default-time="defaultTimeOptions"
                  :shortcuts="shortcuts"
                  range-separator="至"
                  :clearable="false"
                  class="date-picker"
                  :style="{maxWidth: '100%'}"
                />
              </el-form-item>
              <div class="filter-buttons">
                <el-button plain @click="clearData">
                  <el-icon><Refresh /></el-icon>重置
                </el-button>
                <el-button type="primary" @click="submitForm">
                  <el-icon><Search /></el-icon>查询
                </el-button>
              </div>
            </el-form>
          </div>
        </div>
      </div>

      <!-- 数据表格 -->
      <div class="table-card">
        <div class="card-header with-border">
          <h3>执行记录</h3>
          <div class="header-actions">
            <el-button size="small" type="primary" plain @click="exportData">
              <el-icon><Download /></el-icon>导出数据
            </el-button>
          </div>
        </div>

        <el-table
          :data="records"
          v-loading="isLoading"
          element-loading-text="正在加载数据..."
          element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(255, 255, 255, 0.8)"
          class="custom-table"
          :header-cell-style="{ background: '#f8faff', color: '#606266', fontWeight: '600' }"
          border
        >
          <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>

          <el-table-column label="执行时间" align="center" min-width="160">
            <template #default="scope">
              <div class="time-cell">
                <el-icon><Clock /></el-icon>
                <span>{{ $tools.rTime(scope.row.create_time) }}</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="执行人" align="center" min-width="110">
            <template #default="scope">
              <div class="user-cell">
                <el-avatar :size="24" class="user-avatar">{{ scope.row.tester.substring(0, 1) }}</el-avatar>
                <span>{{ scope.row.tester }}</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="环境" align="center" min-width="110">
            <template #default="scope">
              <el-tag effect="dark" :type="getEnvType(scope.row.env_name)" class="env-tag">
                {{ scope.row.env_name }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column label="执行类型" align="center" min-width="120">
            <template #default="scope">
              <el-tag
                v-if="scope.row.execute_type === '手动执行'"
                effect="plain"
                type="primary"
                class="type-tag">
                <el-icon><User /></el-icon> {{ scope.row.execute_type }}
              </el-tag>
              <el-tag
                v-else-if="scope.row.execute_type === '定时执行'"
                effect="plain"
                type="success"
                class="type-tag">
                <el-icon><AlarmClock /></el-icon> {{ scope.row.execute_type }}
              </el-tag>
              <el-tag v-else effect="plain" type="info" class="type-tag">
                <el-icon><QuestionFilled /></el-icon> 未知
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column label="测试计划" align="center" min-width="120">
            <template #default="scope">
              <div class="plan-cell">
                <el-icon><Tickets /></el-icon>
                <span>{{ scope.row.plan_name }}</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="执行情况" align="center" min-width="220">
            <template #default="scope">
              <div v-if="scope.row.status === '执行中'" class="running-status">
                <div class="pulse-dot"></div>
                <span>正在执行中...</span>
              </div>
              <div v-else class="result-container">
                <div class="progress-bar">
                  <el-progress
                    :percentage="Number(scope.row.pass_rate)"
                    :color="getStatusColorGradient(scope.row.pass_rate)"
                    :stroke-width="8"
                    :show-text="false"
                  ></el-progress>
                </div>
                <div class="result-stats">
                  <div class="stat-item pass">
                    <el-icon><Check /></el-icon>
                    <span>{{ scope.row.success }}</span>
                  </div>
                  <div class="stat-item total">
                    <el-icon><Document /></el-icon>
                    <span>{{ scope.row.all }}</span>
                  </div>
                  <div class="stat-item rate" :style="{color: getStatusColor(scope.row.pass_rate)}">
                    {{ scope.row.pass_rate }}%
                  </div>
                </div>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="操作" align="center" width="160">
            <template #default="scope">
              <div class="action-buttons">
                <el-button
                  v-if="scope.row.status !== '执行中'"
                  type="primary"
                  size="small"
                  @click="$router.push({ name: 'report', params: { id: scope.row.id } })"
                >
                  <el-icon><View /></el-icon>查看
                </el-button>
                <span v-else class="running-badge">
                  <el-icon><Loading /></el-icon> 执行中
                </span>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
  </div>
  </el-scrollbar>
</template>

<script>
import { mapState } from 'vuex';
import { 
  DataLine, 
  Check, 
  Loading, 
  PieChart, 
  Refresh, 
  Search, 
  Download, 
  Clock, 
  User, 
  AlarmClock, 
  QuestionFilled, 
  Tickets, 
  Document, 
  View 
} from '@element-plus/icons-vue';

const moment = require('moment-timezone');
function convertToTimeZoneFormat(dateStr, timeZone) {
  const m = moment.tz(dateStr, timeZone);
  return m.format('YYYY-MM-DD HH:mm:ss');
}

function getFormattedDate(date, endOfDay = false) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  let hours, minutes, seconds;

  if (endOfDay) {
    hours = '23';
    minutes = '59';
    seconds = '59';
  } else {
    hours = '00';
    minutes = '00';
    seconds = '00';
  }

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

export default {
  components: {
    DataLine,
    Check,
    Loading,
    PieChart,
    Refresh,
    Search,
    Download,
    Clock,
    User,
    AlarmClock,
    QuestionFilled,
    Tickets,
    Document,
    View
  },
  data() {
    return {
      isLoading: false,
      records: [],
      timeRange: 'day3',
      dataTime: [getFormattedDate(new Date(new Date().getTime() - 2 * 24 * 60 * 60 * 1000)),
                getFormattedDate(new Date(), true)],
      defaultTimeOptions: ['00:00:00', '23:59:59'],
      shortcuts: [
        {
          text: '今天',
          value: (() => {
            const end = new Date();
            const start = new Date();
            start.setHours(0, 0, 0);
            end.setHours(23, 59, 59);
            return [start, end];
          })
        },
        {
          text: '近三天',
          value: (() => {
            const end = new Date();
            const start = new Date();
            start.setDate(end.getDate() - 2);
            start.setHours(0, 0, 0);
            end.setHours(23, 59, 59);
            return [start, end];
          })
        },
        {
          text: '近七天',
          value: (() => {
            const end = new Date();
            const start = new Date();
            start.setDate(end.getDate() - 6);
            start.setHours(0, 0, 0);
            end.setHours(23, 59, 59);
            return [start, end];
          })
        },
        {
          text: '近一个月',
          value: (() => {
            const end = new Date();
            const start = new Date();
            start.setMonth(end.getMonth() - 1);
            start.setHours(0, 0, 0);
            end.setHours(23, 59, 59);
            return [start, end];
          })
        }
      ],
      currentPage: 1,
      pageSize: 10
    };
  },

  methods: {
    submitForm() {
      this.getAllRecord();
    },

    clearData() {
      this.dataTime = [
        getFormattedDate(new Date(new Date().getTime() - 2 * 24 * 60 * 60 * 1000)),
        getFormattedDate(new Date(), true)
      ];
    },

    handleTimeRangeChange(value) {
      const now = new Date();
      let startDate;
      if (value === 'day') {
        startDate = new Date();
        startDate.setDate(now.getDate());
      } else if (value === 'day3') {
        startDate = new Date();
        startDate.setDate(now.getDate() - 2);
      }  else if (value === 'week') {
        startDate = new Date();
        startDate.setDate(now.getDate() - 6);
      } else if (value === 'month') {
        startDate = new Date();
        startDate.setDate(now.getDate() - 29);
      } else if (value === 'all') {
        // 对于 "全部"，我们可以设置一个很早的日期或者按项目情况调整
        startDate = new Date();
        console.log(startDate)
        startDate.setFullYear(now.getFullYear() - 10);
      }

      this.dataTime = [
        getFormattedDate(startDate),
        getFormattedDate(now, true)
      ];

      this.getAllRecord();
    },

    async getAllRecord() {
      this.isLoading = true;
      
      // 延迟一小段时间确保加载状态显示一致
      await new Promise(resolve => setTimeout(resolve, 100));
      
      const startDate = convertToTimeZoneFormat(this.dataTime[0], 'Asia/Shanghai');
      const endDate = convertToTimeZoneFormat(this.dataTime[1], 'Asia/Shanghai');
      const response = await this.$api.getTestRecord({
        project: this.pro.id,
        start_time: startDate,
        end_time: endDate
      });

      if (response.status == 200) {
        this.records = response.data;
        this.chartView();
        
        // 使用nextTick确保DOM更新后再关闭loading状态
        this.$nextTick(() => {
          this.isLoading = false;
        });
      } else {
        this.isLoading = false;
      }
    },

    chartView() {
      this.$chart.chart3(this.$refs.chart_box, this.pateData.value, this.pateData.label);
    },

    getStatusColor(rate) {
      rate = Number(rate);
      if (rate >= 90) return '#67C23A';
      if (rate >= 70) return '#E6A23C';
      return '#F56C6C';
    },

    getStatusColorGradient(rate) {
      rate = Number(rate);
      if (rate >= 90) return [{color: '#95de64', position: 0}, {color: '#52c41a', position: 1}];
      if (rate >= 70) return [{color: '#ffd666', position: 0}, {color: '#faad14', position: 1}];
      return [{color: '#ff7875', position: 0}, {color: '#f5222d', position: 1}];
    },

    getEnvType(env) {
      const typeMap = {
        '生产环境': 'danger',
        '预发布环境': 'warning',
        '测试环境': 'success',
        '开发环境': 'info'
      };
      return typeMap[env] || 'primary';
    },

    handleSizeChange(val) {
      this.pageSize = val;
    },

    handleCurrentChange(val) {
      this.currentPage = val;
    },

    exportData() {
      // Inform the user that the export feature is not yet implemented
       this.$message({
        message: '导出功能尚未实现，敬请期待！',
        type: 'warning',
        duration: 3000
      });
    }
  },

  computed: {
    ...mapState(['pro']),

    pateData() {
      let run_date = [];
      let pass_rate = [];
      for (let item of this.records) {
        run_date.push(this.$tools.rTime(item.create_time));
        pass_rate.push(item.pass_rate);
      }
      return {
        label: run_date,
        value: pass_rate
      };
    },

    totalSuccess() {
      return this.records.reduce((sum, record) => {
        return sum + (record.status !== '执行中' ? parseInt(record.success) || 0 : 0);
      }, 0);
    },

    runningCount() {
      return this.records.filter(record => record.status === '执行中').length;
    },

    averagePassRate() {
      const validRecords = this.records.filter(r => r.status !== '执行中' && r.pass_rate);
      if (validRecords.length === 0) return 0;

      const sum = validRecords.reduce((sum, record) => {
        return sum + parseFloat(record.pass_rate);
      }, 0);

      return Math.round(sum / validRecords.length);
    },

    recordsCount() {
      return this.records.length;
    }
  },

  watch: {
    timeRange(newValue) {
      // Call handleTimeRangeChange when timeRange changes
      this.handleTimeRangeChange(newValue);
    }
  },

  created() {
    // 先将isLoading设为true，保证显示一致性
    this.isLoading = true;
    this.getAllRecord();
  },

  mounted() {
    // 确保在挂载后样式已经应用
    this.$nextTick(() => {
      // 如果数据已加载完成，强制更新一次视图
      if (!this.isLoading && this.records.length > 0) {
        this.$forceUpdate();
      }
    });
  }
};
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
  background-color: #f0f2f5;
  min-height: 100%;
}

/* 统计卡片样式 */
.stats-container {
  display: grid;
  grid-template-columns: repeat(4, minmax(240px, 1fr)); /* 明确4列 */
  gap: 24px;
  margin-bottom: 24px; /* 添加底部间距确保布局稳定 */
  min-height: 120px; /* 确保即使在加载状态也有最小高度 */
  width: 100%;
}

/* 确保在不同状态下保持一致的布局 */
.stats-container.stats-loaded {
  opacity: 1;
  transition: opacity 0.3s ease;
}

.stat-card {
  position: relative;
  border-radius: 10px;
  padding: 24px;
  color: white;
  overflow: hidden;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  display: flex;
  align-items: center;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}

.stat-card:after {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background: rgba(255, 255, 255, 0.1);
  pointer-events: none;
  opacity: 0;
  transition: opacity 0.3s;
  border-radius: 10px;
}

.stat-card:hover:after {
  opacity: 1;
}

.primary-gradient {
  background: linear-gradient(135deg, #1890ff, #096dd9);
}

.success-gradient {
  background: linear-gradient(135deg, #52c41a, #389e0d);
}

.warning-gradient {
  background: linear-gradient(135deg, #faad14, #d48806);
}

.info-gradient {
  background: linear-gradient(135deg, #722ed1, #531dab);
}

.stat-icon {
  height: 56px;
  width: 56px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28px;
  margin-right: 20px;
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 26px;
  font-weight: 600;
  margin-bottom: 4px;
  line-height: 1.2;
  white-space: nowrap;
  color: rgba(255, 255, 255, 0.8);
}

.stat-title {
  font-size: 14px;
  opacity: 0.9;
  white-space: nowrap;
}

/* 图表和过滤器布局 */
.chart-filter-container {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 24px;
  margin-bottom: 24px;
}

.chart-card, .filter-card, .table-card {
  background: white;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  transition: box-shadow 0.3s ease;
}

.chart-card:hover, .filter-card:hover, .table-card:hover {
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
}

.card-header {
  padding: 16px 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #f0f0f0;
}

.card-header.with-border {
  border-bottom: 1px solid #f0f0f0;
}

.card-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #262626;
}

.chart-wrapper {
  padding: 16px;
  height: 320px;
  min-height: 320px; /* 确保最小高度一致 */
}

/* 确保内容在加载状态时保持稳定 */
.el-scrollbar__wrap {
  overflow-x: hidden;
}

/* 确保表格在加载时的高度稳定 */
.table-card {
  min-height: 200px;
  margin-top: 24px;
}

/* 筛选器样式 */
.filter-content {
  padding: 20px;
}

.date-range-item {
  margin-bottom: 20px;
}

.date-picker {
  width: 100%;
  max-width: 100%;
}

.filter-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 10px;
}

/* 表格样式 */
.custom-table {
  margin: 0;
  font-size: 14px;
}

.custom-table :deep(td) {
  padding: 12px 0;
  height: auto;
  line-height: 1.5;
}

.custom-table :deep(th) {
  padding: 12px 0;
  height: 50px;
  font-weight: 600;
}

.time-cell, .user-cell, .plan-cell {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  line-height: 1.5;
  text-align: center;
}

.user-avatar {
  background-color: #1890ff;
  color: white;
}

.env-tag, .type-tag {
  padding: 4px 8px;
  border-radius: 4px;
  line-height: 1.5;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
}

.running-status {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  color: #faad14;
  font-weight: 500;
}

.pulse-dot {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background-color: #faad14;
  position: relative;
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0% {
    transform: scale(0.8);
    box-shadow: 0 0 0 0 rgba(250, 173, 20, 0.7);
  }
  70% {
    transform: scale(1);
    box-shadow: 0 0 0 6px rgba(250, 173, 20, 0);
  }
  100% {
    transform: scale(0.8);
  }
}

.result-container {
  padding: 0 16px;
  min-width: 220px;
}

.progress-bar {
  margin-bottom: 10px;
}

.result-stats {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: nowrap;
  margin-top: 8px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 13px;
  white-space: nowrap;
  padding: 0 8px;
}

.stat-item.pass {
  color: #52c41a;
}

.stat-item.total {
  color: #8c8c8c;
}

.stat-item.rate {
  font-weight: 600;
  font-size: 14px;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 8px;
  flex-wrap: wrap;
}

.running-badge {
  display: inline-flex;
  align-items: center;
  gap: 5px;
  color: #faad14;
  font-size: 13px;
}

.pagination-container {
  padding: 16px 24px;
  display: flex;
  justify-content: flex-end;
  border-top: 1px solid #f0f0f0;
  flex-wrap: wrap;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .chart-filter-container {
    grid-template-columns: 1fr;
  }

  .stats-container {
    grid-template-columns: repeat(2, 1fr);
    gap: 16px;
  }

  .date-picker:deep(.el-range-editor) {
    width: 100% !important;
  }
}

@media (max-width: 768px) {
  .dashboard-container {
    padding: 16px;
  }

  .stats-container {
    grid-template-columns: 1fr;
    gap: 16px;
    margin-bottom: 16px;
  }

  .stat-card {
    padding: 16px;
  }

  .stat-icon {
    height: 48px;
    width: 48px;
    font-size: 24px;
  }

  .stat-value {
    font-size: 24px;
  }

  .chart-filter-container {
    gap: 16px;
    margin-bottom: 16px;
  }

  .filter-content {
    padding: 16px;
  }

  .chart-wrapper {
    height: 260px;
  }

  .date-picker:deep(.el-range-editor) {
    width: 100% !important;
    flex-direction: column;
    height: auto;
  }

  .date-picker:deep(.el-range-separator) {
    padding: 5px 0;
  }

  .date-picker:deep(.el-range-input) {
    width: 100%;
  }
}

@media (max-width: 1300px) {
  .action-buttons {
    flex-direction: column;
    align-items: center;
  }

  .action-buttons .el-button {
    margin-left: 0;
    margin-bottom: 8px;
  }
}

/* 添加表格行条纹效果 */
.custom-table :deep(.el-table__row:nth-child(even)) {
  background-color: #fafafa;
}

/* 确保表格有表头边界 */
.custom-table :deep(.el-table__header) {
  border-bottom: 1px solid #ebeef5;
}

/* 确保测试计划内容不被截断 */
.plan-cell span {
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  display: inline-block;
}

/* 调整操作按钮 */
.action-buttons .el-button {
  padding: 6px 12px;
}

/* 确保内容垂直居中 */
.custom-table :deep(.cell) {
  padding-top: 0;
  padding-bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}
</style>
